package section6_5;

import java.util.Date;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

/**
 * Created by Hyman on 2017/6/15.
 *
 * 使用带有延迟元素的线程安全列表 DelayQueue
 */
public class Main {

    public static void main(String[] args) throws InterruptedException {

        DelayQueue<Event> queue = new DelayQueue<>();

        // 存储5个线程对象的数组
        Thread[] taskThreads = new Thread[5];

        // 创建5个线程运行5个任务，每个任务创建1000事件对象
        for(int i=0; i<taskThreads.length; i++) {
            Task task = new Task(i, queue);
            taskThreads[i] = new Thread(task);
        }

        //  启动5个线程
        for (Thread taskThread : taskThreads) {
            taskThread.start();
        }

        // 等待5个线程完成
        for (Thread taskThread : taskThreads) {
            try {
                taskThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        do {
            int counter = 0;
            Event event;
            do{
                event = queue.poll();
                if(event != null) {
                    counter++;
                }
            } while(event != null);
            System.out.printf("At %s you have read %d events\n", new Date(), counter);
            TimeUnit.MILLISECONDS.sleep(500);
        } while(queue.size() > 0);
    }

}
